/* ******************************************************************************
* 2019 - present Contributed by Apulis Technology (Shenzhen) Co. LTD
*
* This program and the accompanying materials are made available under the
* terms of the MIT License, which is available at
* https://www.opensource.org/licenses/MIT
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: MIT
***************************************************************************** */
package logquery

import (
	"fmt"
	"github.com/grafana/loki/pkg/logcli/client"
	"github.com/grafana/loki/pkg/loghttp"
	"time"
)

// lokiAddr: "192.168.3.137:3100"
// quiet: 是否不打印debug信息
// {namespace=~".+"}  查询包含有这个label的所有日志
func QueryRange(lokiAddr string,
	streamSelectorInclude, streamSelectorExclude map[string]string,
	contentInclude, contentExclude []string,
	limit int,
	from, through time.Time,
	query bool) (res []loghttp.Entry, err error) {
	queryStr := ""
	streamSelectorStr := getStreamSelector(streamSelectorInclude, streamSelectorExclude)
	queryStr = streamSelectorStr
	contentStr := getContent(contentInclude, contentExclude)
	if len(contentStr) > 0 {
		queryStr += contentStr
	}

	//fmt.Println("queryStr: ", queryStr)

	lokiClient := client.DefaultClient{Address: "http://" + lokiAddr}

	data, err := lokiClient.QueryRange(queryStr, limit, from, through, 1, 0, 0, query)
	if err != nil {
		fmt.Printf("err: %+v\n", err)
		return
	}

	//var dataTmp interface{}
	//data.Data.UnmarshalJSON(&dataTmp)
	streams, ok := data.Data.Result.(loghttp.Streams)
	if !ok {
		fmt.Println("unknown log data type")
		err = fmt.Errorf("unknown log data type: %v", data.Data.Result.Type())
		return
	}

	for _, s := range streams {
		res = append(res, s.Entries...)
	}
	return

}

// 获取标签列表
func Label(lokiAddr string,
	quiet bool,
	from, through time.Time) ([]string, error) {
	lokiClient := client.DefaultClient{Address: "http://" + lokiAddr}

	data, err := lokiClient.ListLabelNames(quiet, from, through)
	if err != nil {
		fmt.Printf("err: %+v\n", err)
		return nil, err
	}

	return data.Data, nil
}

// 获取标签对应的value
func LabelValues(
	lokiAddr string,
	quiet bool,
	labelName string,
	from, through time.Time) ([]string, error) {
	lokiClient := client.DefaultClient{Address: "http://" + lokiAddr}

	data, err := lokiClient.ListLabelValues(labelName, quiet, from, through)
	if err != nil {
		fmt.Printf("error: get label value faild: %v\n", err)
		return nil, err
	}

	return data.Data, nil
}
